#include "mytcpserver.h"

MyTcpServer::MyTcpServer()
{

}


//单例模式获取MyTcpServer
MyTcpServer &MyTcpServer::getInstance()
{
    //因为是静态变量, 所以整个程序只有这一个, 所以需要套接字的时候直接使用这个getInstance()函数就可以
    static MyTcpServer instance;
    return instance;
}


//有新连接的时候处理
void MyTcpServer::incomingConnection(qintptr handle)
{
    qcout << "new client connect";

    //来一个连接保存一个socket
    MyTcpSocket *pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(handle);

    //存进链表
    m_tcpSocketList.append(pTcpSocket);


    connect(pTcpSocket, SIGNAL(offline(MyTcpSocket*)), this, SLOT(deleteSocket(MyTcpSocket*)));

}

//获取这个tcpsocket链表
QList<MyTcpSocket *> &MyTcpServer::get_m_tcpSocketList()
{
    return m_tcpSocketList;
}

void MyTcpServer::deleteSocket(MyTcpSocket *mysocket)
{
    //在链表中删除对应的socket
    QList<MyTcpSocket*>::iterator it = m_tcpSocketList.begin();
    for(;it!=m_tcpSocketList.end(); it++)
    {
        if(*it == mysocket)
        {
            //定位到对应的socket
            //(*it)->deleteLater();
            //delete it;
            //it = NULL;
            m_tcpSocketList.erase(it);
            break;
        }
    }

    //遍历m_tcpsocketlist
    qcout<<"遍历m_tcpsocketlist, size=" << m_tcpSocketList.size();
    for(int i = 0; i<m_tcpSocketList.size();i++)
    {
        qcout << m_tcpSocketList.at(i)->getName();
    }


}
